﻿using mozhi.smarterp.Finance.Enums;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Domain.Services;
using Volo.Abp.Domain.Entities;
using Mozhi.Abp.Domain.BasicData.Repositories;

namespace mozhi.smarterp.Finance
{
    public class DocumentDomainService<TEntity , TKey> : DomainService where TEntity : class, IEntity<TKey>
    {
        protected IDocumentRepository<TEntity, TKey> _repository;
        protected INumberGeneratorRepository _numberGeneratorRepository;
        protected DocumentType _documentType;

        public DocumentDomainService(IDocumentRepository<TEntity, TKey> repository, INumberGeneratorRepository numberGeneratorRepository, DocumentType documentType)
        {
            _repository = repository;
            _numberGeneratorRepository = numberGeneratorRepository;
            _documentType = documentType;
        }

        protected virtual async Task<string> GetNextNumberAsync()
        {
            var latestNumber = await _repository.GetLatestNumberAsync();

            var numberGenerator = await _numberGeneratorRepository.GetAsync((int)_documentType, latestNumber ?? "");

            if (numberGenerator == null)
                throw new UserFriendlyException($"未设置类型为：{_documentType}的编码规则", "100000");

            return numberGenerator?.Number;
        }
    }
}
